let vditor = null;
let user = null;
let oldQuestion = null;

function initNewQuestion() {
    let newQuestionElement = document.getElementById("new-question");
    newQuestionElement.style.display = "block";
    newQuestionElement.addEventListener("click", async function () {
        let questionTitle = document.getElementById("question-title").value;
        if (questionTitle.trim().length === 0) {
            parent.layui.layer.alert("问题标题不能为空！");
            return;
        }
        if (!user) {
            parent.layui.layer.alert(`当前您未登录，登陆后才能提出问题！`);
            return;
        }
        if (user.role !== "ASKER" && user.role !== "ADMIN") {
            parent.layui.layer.alert(`当前用户没有权限提出问题！`);
            return;
        }

        let questionContent = vditor.getValue();
        // 创建要发送的 JSON 数据
        const question = {
            userId: user.id,
            title: questionTitle,
            content: questionContent
        };
        try {
            // 使用 fetch API 发送 POST 请求
            const response = await fetch('/api/question', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(question)
            });

            if (!response.ok) {
                parent.layui.layer.alert(`由于网络原因，新增问题失败！状态码：` + response.statusText);
                throw new Error('Network response was not ok ' + response.statusText);
            }

            const result = await response.json();

            // 根据返回结果进行处理，显示成功信息
            parent.layui.layer.alert(`新增问题成功！`);

            // 关闭弹窗
            var index = parent.layui.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layui.layer.close(index);

            parent.location.reload();

        } catch (error) {
            parent.layui.layer.alert(`新增问题出错！` + error);
            console.error('新增问题出错 There was a problem with the fetch operation:', error);
        }
    });
}

async function initOldQuestion() {
    await fetch(`/api/question/${questionId}`)
        .then(response => {
            if (!response.ok) {
                parent.layui.layer.alert(`获取问题出错！<br />状态码：${response.status}`);
                return;
            }
            return response.json();
        })
        .then(data => {
            oldQuestion = data;
            document.getElementById("question-title").value = oldQuestion.title;
            vditor.setValue(oldQuestion.content);
        })
        .catch(error => {
            parent.layui.layer.msg('因网络原因，获取问题失败！');
            console.error('Error:', error);
        });
}


async function initEditQuestion() {
    await initOldQuestion();
    if (!oldQuestion) {
        vditor.setValue("# 获取问题出错，请稍后重试！");
        return;
    }
    let editQuestionElement = document.getElementById("edit-question");
    editQuestionElement.style.display = "block";
    editQuestionElement.addEventListener("click", async function () {
        let questionContent = vditor.getValue();
        let questionTitle = document.getElementById("question-title").value;
        if (questionTitle.trim().length === 0) {
            parent.layui.layer.alert("问题标题不能为空！");
            return;
        }
        if (!user) {
            parent.layui.layer.alert(`当前您未登录，登陆后才能修改问题！`);
            return;
        }
        if (user.role !== "ASKER" && user.role !== "ADMIN") {
            parent.layui.layer.alert(`当前用户没有修改修改问题！`);
            return;
        }
        // 创建要发送的 JSON 数据
        const question = {
            id: questionId,
            title: questionTitle,
            content: questionContent
        };
        try {
            // 使用 fetch API 发送 POST 请求
            const response = await fetch('/api/question', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(question)
            });

            if (!response.ok) {
                parent.layui.layer.alert(`由于网络原因，修改问题失败！状态码：` + response.statusText);
                throw new Error('Network response was not ok ' + response.statusText);
            }

            const result = await response.json();

            // 根据返回结果进行处理，显示成功信息
            parent.layui.layer.alert(`修改问题成功！`);


            // 关闭弹窗
            var index = parent.layui.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layui.layer.close(index);

            let answerWindow = parent.document.getElementById("answer-iframe").contentWindow;
            answerWindow.initQuestion();

        } catch (error) {
            parent.layui.layer.alert(`修改问题出错！` + error);
            console.error('修改问题出错 There was a problem with the fetch operation:', error);
        }
    });
}

function initVditor() {
    vditor = new Vditor('vditor', {
        height: "100%",
        placeholder: '请输入问题内容',
        cache: {
            enable: false
        },
        after: function () {
            questionId = getQueryVariable("question-id");
            if (!questionId) {
                initNewQuestion();
            } else {
                initEditQuestion();
            }
        }
    });
}


async function initUser() {
    return await fetch('/api/auth/user')
        .then(response => {

            if (!response.ok && (response.status < 400 && response.status >= 500)) {
                parent.layui.layer.alert(`获取当前用户信息出错！<br />状态码：${response.status}`);
                return false;
            }

            if (!response.ok) {
                parent.layui.layer.alert(`当前您未登录！`);
                return false;
            }

            response.json().then(data => {
                user = data;
            });

            return true;
        })
        .catch(error => {
            parent.layui.layer.msg('因网络原因，获取用户信息失败！');
            console.error('Error:', error);
            return false;
        });
}

document.addEventListener('DOMContentLoaded', () => {
    layui.use(async function () {
        initVditor();
        await initUser();
    });
});
